<template>
	<view class="container">
		<NavBar :isRight="true" :isLeft="true" :licon="'back'" class="nav-search" :style="topBarStyle"
			@onLeft="onLeftIcon">
			<template #lc>
				<view class="center item">
					<common-tab :current="current" :tab-list="tabList" :lineWidth="50" :itemWidth="140"
						@change="changeTabIndex">
					</common-tab>
				</view>
			</template>
			<template #lr>
				<view class="nav-right">
					<!-- <u-icon name="search" size="28" @click="navigateToSearchPage" color="#000"></u-icon> -->
					<view class="nav-bar-lr" id="bingEleId">
						<bubble icon="personadd" :showBubble="showBubble" :dataList="bubbleList" bubblePosition="bottom"
							@change="changeBubble" @onIconItem="onIconItem"></bubble>
					</view>
				</view>
			</template>
		</NavBar>

		<view class="navbar-background-image">
			<image src="http://www.hacn86.cn/AI_QA/2025/07/10/1752136587830_20250710163627A008.png" mode="aspectFill">
			</image>
		</view>

		<view class="page-content" @touchstart="touchStart" @touchend="touchEnd">
			<!-- 互关 -->
			<u-index-list v-if="current==0" @select="onInsexList" :indexList="indexList" class="index-list-container">
				<view class="" @click="navigateToSearchPage" style="margin:30rpx 30rpx 40rpx;">
					<u-search :showAction="false" shape="square" placeholder="搜索" bgColor="#F3F2F2"></u-search>
				</view>

				<u-index-item>
					<view class="index-list-item">
						<view class="avatar">
							<image src="/static/make-friends/groupChat.png" mode=""></image>
						</view>
						<view class="name">群聊</view>
					</view>
				</u-index-item>
				<template v-for="(item, index) in groupedArray">
					<u-index-item>
						<u-index-anchor :text="indexList[index]" bgColor="#fff"></u-index-anchor>
						<view class="index-list-item" v-for="(cell, i) in item" :key="i" @click="toHomePage(cell)">
							<u-avatar mode="aspectFill" :src="cell.avatar"></u-avatar>
							<view class="name">{{cell.nickName}}</view>
						</view>
					</u-index-item>
				</template>
			</u-index-list>


			<!-- (2)消息列表 (仅在 App 和 H5 显示) -->
			<!-- #ifdef APP-PLUS || H5 -->
			<uni-list v-if="current==1" :border="false">
				<!-- 头像显示角标 -->
				<view v-for="(item , i) in processedSessionList" @longpress="onLongPress(item)" :key="i">
					<uni-list-chat :clickable="true" :avatar-circle="true" :title="item.name" :avatar="item.avatar"
						:note="item.note" :time="item.time" :badge-text="item.badge"
						@click="onChat(item)"></uni-list-chat>
					<view class="hr"></view>
				</view>
				<u-empty v-if="processedSessionList.length === 0" mode="message" text="暂无消息" marginTop="100"></u-empty>
			</uni-list>
			<!-- #endif -->
			<!-- 小程序端的消息Tab占位符 -->
			<!-- #ifndef APP-PLUS || H5 -->
			<u-empty v-if="current==1" mode="message" text="消息功能在此平台不可用"></u-empty>
			<!-- #endif -->




			<!-- （3）似曾相识 -->
			<view v-if="current==2">
				<view class="friends-add">
					<u-search shape="square" searchIcon="arrow-down-fill" searchIconSize="10" borderColor="#979797"
						bgColor="#FFFFFF" searchIconColor="#000000" label="找人" placeholder="学校/居住/老家/手机号等"
						@focus="navigateToFriendSearch" :showAction="false">
					</u-search>
					<view class="friends-add-icon-box">
						<view class="friends-add-icon-box-item" @click="onIcon(0)">
							<u-icon name="scan" size="35" color="#000000"></u-icon>
							<text>扫一扫</text>
						</view>
						<view class="friends-add-icon-box-item" @click="onIcon(1)">
							<u-icon name="phone" size="35" color="#000000"></u-icon>
							<text>手机联系人</text>
						</view>
						<view class="friends-add-icon-box-item" @click="onIcon(2)">
							<u-icon name="man-add" size="35" color="#000000"></u-icon>
							<text>面对面添加</text>
						</view>
						<view class="friends-add-icon-box-item" @click="onIcon(3)">
							<u-icon name="eye" size="35" :color="isNear?'#1195DA':'#000000'"></u-icon>
							<text :style="isNear?'color:#1195DA':''">附近的人</text>
						</view>
					</view>
					<view class="title">{{!isNear?'似曾相识的人':'附近的人'}}</view>
				</view>

				<uni-list :border="false">
					<uni-list-item :border="false" clickable @click="onChat(item)" v-for="(item, index) in personList"
						:key="index">
						<template v-slot:header>
							<u-avatar :src="item.avatar||''" mode="aspectFill" size="90rpx"></u-avatar>
						</template>
						<template v-slot:body>
							<view class="slot-box">
								<view class="slot-box-name">
									<view class="slot-box-name-left">{{item.name}}</view>
									<view class="slot-box-sex">
										<u-icon v-if="!item.sex" name="woman" color="#EA0B8B" size="15"></u-icon>
										<u-icon v-else name="man" color="#00A6EE" size="15"></u-icon>{{item.age}}岁
									</view>
								</view>
								<view class="slot-text" v-if="!isNear">
									{{item.note}}
								</view>
								<view class="slot-text" v-if="isNear">
									个性签名：{{item.sign}}
								</view>
							</view>
						</template>
						<template v-slot:footer>
							<view class="slot-image" v-if="!isNear">
								<u-button style="height: 50rpx;" size="small" text="添加" @click="onAddFriend"></u-button>
							</view>
							<view class="slot-image" v-if="isNear">
								<view class="">
									{{item.range}}km
								</view>
								<u-button text="打招呼" size="mini" @click="onSayHello"
									color="linear-gradient(to right, rgb(23,185,252), rgb(66,105,248))"></u-button>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</view>

		<uni-icons custom-prefix="custom-icon" type="icon-youxi" size="30"></uni-icons>
		<u-popup :show="show" mode="left" :closeable="true" :closeOnClickOverlay="true" @close="close" @open="open">
			<view style="margin-top: 100rpx;width: 500rpx;">
				<u-empty mode="data" text="侧边栏暂空"></u-empty>
			</view>
		</u-popup>
		<!-- 长按菜单 -->
		<u-action-sheet :actions="longList" :show="showLong" :cancelText="'取消'" :closeOnClickOverlay="true"
			:closeOnClickAction="true" @select="showLong = false" @close="showLong = false"></u-action-sheet>
	</view>
</template>

<script>
	import Bubble from '@/components/friends/bubble/bubble.vue';
	import NavBar from "@/components/common-nav/common-nav.vue"
	import CommonTab from '@/components/common-tab/common-tab.vue';

	import {
		getFriendsList
	} from '@/request/api.js'
	import {
		mapState,
		mapActions
	} from 'vuex'; // 引入Vuex辅助函数
	import processScanResult from '@/utils/scan-processor.js';



	export default {
		components: {
			NavBar,
			CommonTab,
			Bubble
		},
		data() {
			return {
				qlIcon: require('@/static/make-friends/icon_ql_1.png'),
				touchStartX: 0,
				touchStartY: 0,
				showBubble: false,
				isNear: false,
				current: 1,
				show: false,
				tabList: [{
					name: '朋友'
				}, {
					name: '消息'
				}, {
					name: '似曾相识'
				}],
				bubbleList: [{
						current: 1,
						text: '发起群聊',
						iconSrc: require('@/static/make-friends/icon_ql.png')
					},
					{
						current: 2,
						text: '添加好友',
						iconSrc: require('@/static/make-friends/icon_tjhy.png')
					},
					{
						current: 3,
						text: '扫一扫',
						iconSrc: require('@/static/make-friends/icon_sys.png')
					}
				],
				indexList: [],
				groupedArray: [],
				personList: [{
						avatar: "",
						name: "尽揽少女心",
						age: 255,
						sex: 0,
						range: 5.3,
						sign: "深自缄默 如云漂泊橘色棉花糖 ",
						note: "你和她有20个共同好友.同样来自西沙小学"
					},
					{
						avatar: "",
						name: "大道至简",
						age: 25,
						sex: 1,
						range: 5.3,
						sign: "时间会告诉你，伴你到最后不是旧..",
						note: "你和她有20个共同好友.同样来自西沙小学"
					}
				],
				showLong: false,
				longList: [{
						name: '标为已读'
					},
					{
						name: '置顶聊天'
					},
					{
						name: '删除'
					}
				],
				scrollTop: 0,
				old: {
					scrollTop: 0
				}
			}
		},
		computed: {
			// 从Vuex的im模块中映射会话列表状态
			...mapState('im', ['sessionList']),

			// 从Vuex的根state中获取好友列表
			friendList() {
				return this.$store.state.friendList || [];
			},
			// 新增/修改：创建处理和格式化 sessionList 的计算属性
			processedSessionList() {
				if (!this.sessionList) return [];
				// 格式化从后端获取的 sessionList 用于UI展示
				return this.sessionList.map(session => {
					// 格式化最后一条消息内容
					let note = '[新消息]'; // 默认提示
					if (session.lastMessageType === 'txt') {
						note = session.lastMessage ? session.lastMessage : '[新消息]';
					} else if (session.lastMessageType === 'img') {
						note = '[图片]';
					} else if (session.lastMessageType === 'audio') {
						note = '[语音]';
					} else if (session.lastMessageType === 'video') {
						note = '[视频]';
					} else if (session.lastMessageType) {
						note = `[${session.lastMessageType}]`;
					}

					return {
						...session,
						name: session.nickName, // 后端字段
						avatar: session.avatarUrl, // 后端字段
						note: note,
						time: this.formatTimestamp(session.lastMessageTime), // 后端字段
						badge: session.unreadCount > 0 ? String(session.unreadCount) : '',
						// 为导航到聊天页面准备参数
						userId: session.targetId, // 后端字段
						nickName: session.nickName, // 后端字段
						group_chat: session.type === '1' // 后端字段，假设 '1' 代表群聊
					};
				});
			},
			topBarStyle() {
				// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
				console.log("this.$store.state.systemInfo", this.$store.state.systemInfo);
				if (this.$store.state.systemInfo.capsuleInfo.width > 0) {
					const paddingRight = this.$store.state.systemInfo.capsuleInfo.width + this.$store.state.systemInfo
						.capsuleRightPadding * 2;
					const paddingTop = this.$store.state.systemInfo.statusBarHeight + this.$store.state.systemInfo
						.capsuleRightPadding + 40
					return `padding-right: ${paddingRight}px;padding-top:${paddingTop}px`;
				}
				// #endif

				// 在非小程序平台或计算完成前，返回一个空字符串
				return '';
			}
		},
		onLoad() {
			this.initData();
		},
		onReady() {},
		onShow() {
			// #ifdef APP-PLUS || H5
			if (this.current === 1) { // 如果当前是消息tab
				this.fetchSessionList();
			}
			// #endif
		},
		onUnload() {},
		methods: {
			// 映射 'im' 模块中的 actions
			...mapActions('im', ['fetchSessionList']),

			initData() {
				this.getFriendsList()
				this.fetchSessionList();
			},
			// 格式化时间戳，用于显示
			formatTimestamp(timestamp) {
				if (!timestamp) return '';
				const now = new Date();
				const msgDate = new Date(timestamp);

				if (now.toDateString() === msgDate.toDateString()) {
					// 今天: 显示 HH:mm
					return `${msgDate.getHours().toString().padStart(2, '0')}:${msgDate.getMinutes().toString().padStart(2, '0')}`;
				} else if (now.getFullYear() === msgDate.getFullYear()) {
					// 今年: 显示 MM-DD
					return `${(msgDate.getMonth() + 1).toString().padStart(2, '0')}-${msgDate.getDate().toString().padStart(2, '0')}`;
				} else {
					// 更早: 显示 YYYY-MM-DD
					return `${msgDate.getFullYear()}-${(msgDate.getMonth() + 1).toString().padStart(2, '0')}-${msgDate.getDate().toString().padStart(2, '0')}`;
				}
			},

			// 获取用户通讯录列表
			getFriendsList() {
				getFriendsList().then(res => {
					this.groupedArray = res.data.data.groupedArray
					this.indexList = res.data.data.indexArray
					this.handleData()
				})
			},

			handleData() {
				let list = []
				this.groupedArray.forEach(item => {
					let listItem = []
					listItem = item.map(i => {
						return {
							name: i.nickName,
							id: i.userId,
							avatar: i.avatar,
						}
					})
					list.push(...listItem)
				})
				this.$store.commit("setFriendList", list)
			},

			// 进入聊天页面
			onChat(item) {
				const userParam = {
					userId: item.userId,
					nickName: item.nickName,
					avatar: item.avatar,
				};
				uni.navigateTo({
					url: `/pages_sub/user/chat/chat?user=${JSON.stringify(userParam)}&group=${item.group_chat}`
				});
			},

			// 响应子组件tab切换
			changeTabIndex(index) {
				// #ifndef APP-PLUS || H5
				// 小程序中，tab的index需要映射。如果原index 1是消息，现在可能不存在了
				// 假设小程序tabList是 ['通讯录', '似曾相识']
				// 点击第一个，index=0 -> current=0 (通讯录)
				// 点击第二个，index=1 -> current=2 (似曾相识)
				if (index === 1) {
					this.current = 2;
				} else {
					this.current = index;
				}
				// #endif

				// #ifdef APP-PLUS || H5
				this.current = index;
				if (index === 1) {
					this.fetchSessionList();
				}
				// #endif
				this.current = index;
			},

			touchStart(e) {
				this.touchStartX = e.touches[0].clientX;
				this.touchStartY = e.touches[0].clientY;
				this.showBubble = false
			},

			touchEnd(e) {
				let deltaX = e.changedTouches[0].clientX - this.touchStartX;
				let deltaY = e.changedTouches[0].clientY - this.touchStartY;
				if (Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {
					if (deltaX >= 0) {
						this.current = this.current - 1 < 0 ? this.current : this.current - 1
						this.changeTabIndex(this.current)
					} else {
						this.current = this.current + 1 > 2 ? this.current : this.current + 1
						this.changeTabIndex(this.current)
					}
				}
			},

			// 其余方法保持不变
			onLongPress() {
				this.showLong = true
			},
			onLeftIcon() {
				uni.navigateBack();
			},
			changeBubble(a) {
				this.showBubble = a
			},
			onInsexList(e) {
				console.log(e);
			},
			toHomePage(item) {
				uni.navigateTo({
					url: '/pages_sub/user/others/others?userId=' + item.userId
				});
			},
			navigateToSearchPage() {
				uni.navigateTo({
					url: '/pages_sub/common/search-user/search-user'
				})
			},
			navigateToFriendSearch() {
				uni.navigateTo({
					url: '/pages_sub/index/friends/friend-add'
				})
			},
			onIconItem(index) {
				this.showBubble = false
				console.log(index);
				if (index == 1) {
					this.navigateToFriendSearch()
				} else if (index == 2) {
					this.onScanCode()
				}
			},
			onScanCode() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						processScanResult(res.result);
					},
					fail: (err) => {
						if (err.errMsg !== 'scanCode:fail cancel') {
							uni.showToast({
								title: '扫码失败',
								icon: 'none'
							});
						}
					}
				});
			},
			onIcon(current) {
				if (current == 0) {
					this.onScanCode()
				} else if (current == 1) {
					this.getContacts()
				} else if (current == 3) {
					this.isNear = true
				}
			},
			getContacts() {
				uni.navigateTo({
					url: '/pages_sub/friends/phone-contacts'
				})
			},
			onAddFriend() {
				uni.showToast({
					title: '暂时不可添加！',
					icon: "error"
				});
			},
			onSayHello() {
				uni.navigateTo({
					url: '/pages_sub/user/chat/chat'
				});
			},
			open() {},
			close() {
				this.show = false
			},
			upper: function(e) {
				console.log(e)
			},
			lower: function(e) {
				console.log(e)
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 全局样式重写
	::v-deep .uni-list-chat {
		--avatar-width: 50px;
		--avatar-border-radius: 50%;

		.uni-list-chat__header-image {
			border: none;
		}
	}

	// 平台特定样式
	page {
		padding-top: 90rpx !important;
	}

	.container {
		overflow: hidden;

		// NavBar相关样式
		.nav-search {
			.nav-bar-lr {
				width: 50px;
				height: 100%;
				text-align: center;
			}

			.center {
				flex: 1;
			}

			.nav-right {
				display: flex;
			}
		}

		// NavBar底部背景图片
		.navbar-background-image {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 240rpx;
			z-index: 10;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.page-content {
			max-height: calc(100vh - 200rpx);
			position: absolute;
			top: 200rpx;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 11;
			border-radius: 50rpx 50rpx 0 0;
			background-color: rgba(255, 255, 255, 1);
			overflow: hidden;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

			.index-list-item:last-child {
				border: none !important;
			}

			.index-list-item {
				display: flex;
				padding: 20rpx 24rpx;
				color: #323233;
				font-size: 14px;
				line-height: 24px;
				align-items: center;
				border-bottom: 1rpx solid #F8F8F8;

				.avatar {
					width: 88rpx;
					height: 88rpx;
					border-radius: 50%;
					background-color: #FFB327;

					image {
						margin: 16rpx;
						width: 56rpx;
						height: 56rpx;
					}
				}

				.name {
					flex: 1;
					height: 44px;
					line-height: 44px;
					margin-left: 20rpx;
					color: #000000;
					font-size: 30rpx;
					font-weight: 700;
				}
			}

			.tabs-two {
				height: 100%;
			}

			.hr {
				border-bottom: 1rpx solid #F8F8F8;
			}



		}

		// 似曾相识
		.friends-add {
			padding: 30rpx 20rpx;
			font-size: 25rpx;

			&-icon-box {
				display: flex;
				justify-content: space-around;
				background: #F7F7F7;
				border-radius: 20rpx;
				margin: 20rpx 0;
				padding: 20rpx 30rpx;

				&-item {
					display: flex;
					flex-direction: column;
					align-items: center;
				}
			}
		}

		.slot-box {
			display: flex;
			flex-direction: column;
			padding: 0 30rpx;
			height: 90rpx;
			flex: 1;

			.slot-box-name {
				display: flex;
				align-items: center;
				font-size: 20rpx;
				height: 50rpx;
				line-height: 50rpx;
				.slot-box-name-left {
					font-weight: 600;
					font-size: 30rpx;
				}
			}

			.slot-box-sex {
				display: flex;
				background-color: #EEEEEE;
				border-radius: 10rpx;
				height: 30rpx;
				margin-left: 20rpx;
				font-size: 20rpx;
				padding: 5rpx 8rpx;
				line-height: 30rpx;
				color: #999999;
			}

			.slot-image {
				font-size: 24rpx;
				line-height: 40rpx;
				color: #999999;
				text-align: center;
			}

			.slot-text {
				flex: 1;
				font-size: 24rpx;
				line-height: 40rpx;
				color: #999999;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}
	}
</style>